package org.example.sysuser.mapper;

import org.example.Exception.SysUserException;
import org.example.sysuser.entity.SysUser;
import org.example.util.DBUtil;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
持久层接口
 */
public class SysUserMapper {

    public SysUser login(String username, String password) throws RuntimeException {
        Connection conn=null;
        Statement statement=null;
        ResultSet resultSet=null;
        try{
            conn = DBUtil.getConnection();
             statement = conn.createStatement();
        }catch (SQLException e){
            e.printStackTrace();
        }

        SysUser sysUser = null;

        try {
            // 拼接 SQL 时加上引号，防止 SQL 注入攻击（虽不彻底，但比没有强）
            String sql = "SELECT user_id, nick_name, user_name,password FROM sys_user WHERE user_name = '"
                    + username +"'";
            resultSet = statement.executeQuery(sql);

            if (resultSet.next()) {
                sysUser = new SysUser();
                sysUser.setPassword(resultSet.getString("password"));
                sysUser.setUserId(resultSet.getLong("user_id"));
                sysUser.setNickName(resultSet.getString("nick_name"));
                sysUser.setUserName(resultSet.getString("user_name"));
            }
        } finally {
            DBUtil.close(statement, conn, resultSet);
            return sysUser;
        }
    }
    public void register(SysUser sysUser) throws RuntimeException {

        Connection conn;
        Statement statement=null;
        try{
            conn = DBUtil.getConnection();
            statement = conn.createStatement();
        }catch (SQLException e){
            e.printStackTrace();
        }

        String userName = sysUser.getUserName();
        String userEmail = sysUser.getEmail();
        String phone = sysUser.getPhonenumber();
        String sex = sysUser.getSex();
        String loginIp = sysUser.getLoginIp();
        String nickName = sysUser.getNickName();
        String createBy = sysUser.getCreateBy();
        String remark = sysUser.getRemark();
        String pwd = sysUser.getPassword();
        String now = "NOW()";
        // 构建新增的语句
        String sql = String.format(
                "INSERT INTO sys_user (" +
                        "user_name, nick_name, user_type, email, phonenumber, sex, avatar, password, status, del_flag, login_ip, login_date, pwd_update_date, create_by, create_time, update_by, update_time, remark, dept_id" +
                        ") VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s', %s, %s, '%s', %s, '%s', %s, '%s', NULL)",
                userName, nickName, "00", userEmail, phone, sex, "", pwd, "0", "0", loginIp,
                now, now, createBy, now, createBy, now, remark);
        try {
            int count = statement.executeUpdate(sql);
            if (count > 0){
                System.out.println("注册成功！");
            }
        } catch (SQLException e) {
            throw new SysUserException("注册失败！");
        }
    }
    /**
     * 条件查询用户信息
     * @param sysUser
     * @return
     */
    public List<SysUser> selectSysUser(SysUser sysUser) throws SQLException {
        Connection conn=null;
        Statement statement=null;
        ResultSet rs=null;
        List<SysUser> users = new ArrayList<>();
        SysUser resultUser = null;
        boolean hasCondition = false;

        StringBuilder sql = new StringBuilder("SELECT * FROM sys_user WHERE 1=0");

        if (sysUser.getUserName() != null && !sysUser.getUserName().trim().isEmpty()) {
            sql.append(" OR user_name = '").append(sysUser.getUserName()).append("'");
            hasCondition = true;
        }

        if (sysUser.getEmail() != null && !sysUser.getEmail().trim().isEmpty()) {
            sql.append(" OR email = '").append(sysUser.getEmail()).append("'");
            hasCondition = true;
        }

        if (sysUser.getPhonenumber() != null && !sysUser.getPhonenumber().trim().isEmpty()) {
            sql.append(" OR phonenumber = '").append(sysUser.getPhonenumber()).append("'");
            hasCondition = true;
        }

// 如果没有设置任何查询条件，则查询所有用户
        if (!hasCondition) {
            sql = new StringBuilder("SELECT * FROM sys_user");
        }
        // 执行查询
        try {
            conn = DBUtil.getConnection();
            statement = conn.createStatement();
            rs = statement.executeQuery(sql.toString());
            while (rs.next()) {
                resultUser = new SysUser();
                resultUser.setUserId(rs.getLong("user_id"));
                resultUser.setUserName(rs.getString("user_name"));
                resultUser.setNickName(rs.getString("nick_name"));
                resultUser.setPassword(rs.getString("password"));
                resultUser.setPhonenumber(rs.getString("phonenumber"));
                resultUser.setEmail(rs.getString("email"));
                resultUser.setCreateTime(rs.getTimestamp("create_time"));
                resultUser.setStatus(rs.getString("status"));
                resultUser.setDelFlag(rs.getString("del_flag"));
                resultUser.setLoginIp(rs.getString("login_ip"));
                resultUser.setLoginDate(rs.getTimestamp("login_date"));
                resultUser.setPwdUpdateDate(rs.getTimestamp("pwd_update_date"));
                resultUser.setRemark(rs.getString("remark"));
                users.add(resultUser);
            }
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            DBUtil.close(statement,conn,rs);
            return users;
        }
   }
}
